import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'
const ExpiresInKey = 'Admin-Expires-In'
const TokenTimeKey = 'Admin-Token-Time'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

export function getExpiresIn() {
  return Cookies.get(ExpiresInKey) || -1
}

export function setExpiresIn(time) {
  return Cookies.set(ExpiresInKey, time)
}

export function removeExpiresIn() {
  return Cookies.remove(ExpiresInKey)
}

export function getTokenTime() {
  return Cookies.get(TokenTimeKey) || new Date().getTime()
}

export function setTokenTime() {
  return Cookies.set(TokenTimeKey, new Date().getTime())
}

export function removeTokenTime() {
  return Cookies.remove(TokenTimeKey)
}

// 清除所有认证相关的缓存
export function clearAuthCache() {
  removeToken()
  removeExpiresIn()
  removeTokenTime()

  // 只清除认证相关的localStorage项
  const authKeys = [
    'Admin-Token',
    'Admin-Expires-In',
    'Admin-Token-Time',
    'last-force-refresh',
    'sessionObj'
  ]

  authKeys.forEach(key => {
    localStorage.removeItem(key)
    sessionStorage.removeItem(key)
  })

  // 只清除认证相关的cookies
  const authCookieKeys = [TokenKey, ExpiresInKey, TokenTimeKey]
  authCookieKeys.forEach(key => {
    Cookies.remove(key)
    Cookies.remove(key, { path: '/' })
    Cookies.remove(key, { path: '/', domain: window.location.hostname })
  })
}
